<template>
  <div class="skill-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">技能管理系统</h2>
      <div class="header-actions">
        <button class="refresh-btn" @click="forceRefresh" :disabled="loading">
          <span class="refresh-icon">🔄</span>
          {{ loading ? '刷新中...' : '刷新数据' }}
        </button>
        <button class="add-btn" @click="showAddModal = true">
          <span class="add-icon">+</span>
          添加技能
        </button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <div class="search-box">
        <input 
          v-model="searchQuery" 
          type="text" 
          placeholder="搜索技能名称..."
          class="search-input"
          @input="handleSearch"
        />
      </div>
      <div class="filter-box">
        <select v-model="filterHeroId" @change="handleFilter" class="filter-select">
          <option value="">全部英雄</option>
          <option v-for="hero in heroList" :key="hero.id" :value="hero.id">
            {{ hero.heroName }}
          </option>
        </select>
      </div>
    </div>

    <!-- 技能列表表格 -->
    <div class="table-container" v-if="!loading">
      <table class="skill-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>技能名称</th>
            <th>所属英雄</th>
            <th>技能描述</th>
            <th>技能资源</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="skill in paginatedSkills" :key="skill.skillId" class="skill-row">
            <td>{{ skill.skillId }}</td>
            <td class="skill-name-cell">{{ skill.skillName }}</td>
            <td>{{ skill.heroName }}</td>
            <td class="skill-desc-cell">
              <div class="skill-description" :title="skill.skillDescription">
                {{ truncateText(skill.skillDescription, 50) }}
              </div>
            </td>
            <td>
              <a v-if="skill.skillUrl" :href="skill.skillUrl" target="_blank" class="skill-link">
                查看资源
              </a>
              <span v-else class="no-resource">暂无</span>
            </td>
            <td>{{ formatDate(skill.createTime) }}</td>
            <td class="action-cell">
              <button class="edit-btn" @click="editSkill(skill)" title="编辑">
                ✏️
              </button>
              <button class="delete-btn" @click="deleteSkill(skill)" title="删除">
                🗑️
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="totalPages > 1">
      <button 
        class="page-btn" 
        :disabled="currentPage === 1" 
        @click="changePage(currentPage - 1)"
      >
        上一页
      </button>
      <span class="page-info">
        第 {{ currentPage }} 页，共 {{ totalPages }} 页
      </span>
      <button 
        class="page-btn" 
        :disabled="currentPage === totalPages" 
        @click="changePage(currentPage + 1)"
      >
        下一页
      </button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 错误状态 -->
    <div v-if="error" class="error-container">
      <p>{{ error }}</p>
      <button @click="loadSkills" class="retry-btn">重试</button>
    </div>

    <!-- 添加/编辑技能模态框 -->
    <div v-if="showAddModal || showEditModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ showAddModal ? '添加技能' : '编辑技能' }}</h3>
          <button class="close-btn" @click="closeModal">×</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="submitForm">
            <div class="form-group">
              <label>技能名称</label>
              <input v-model="formData.skillName" type="text" required class="form-input" />
            </div>
            <div class="form-group">
              <label>所属英雄</label>
              <select v-model="formData.heroId" required class="form-select">
                <option value="">请选择英雄</option>
                <option v-for="hero in heroList" :key="hero.id" :value="hero.id">
                  {{ hero.heroName }}
                </option>
              </select>
            </div>
            <div class="form-group">
              <label>技能描述</label>
              <textarea v-model="formData.skillDescription" class="form-textarea" rows="4"></textarea>
            </div>
            <div class="form-group">
              <label>技能资源链接</label>
              <input v-model="formData.skillUrl" type="url" class="form-input" placeholder="https://..." />
            </div>
            <div class="form-actions">
              <button type="button" @click="closeModal" class="cancel-btn">取消</button>
              <button type="submit" class="submit-btn" :disabled="submitting">
                {{ submitting ? '提交中...' : (showAddModal ? '添加' : '更新') }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 删除确认模态框 -->
    <div v-if="showDeleteModal" class="modal-overlay" @click="closeDeleteModal">
      <div class="modal-content delete-modal" @click.stop>
        <div class="modal-header">
          <h3>确认删除</h3>
          <button class="close-btn" @click="closeDeleteModal">×</button>
        </div>
        <div class="modal-body">
          <p>确定要删除技能 "{{ skillToDelete?.skillName }}" 吗？</p>
          <p class="warning-text">此操作不可撤销！</p>
          <div class="form-actions">
            <button @click="closeDeleteModal" class="cancel-btn">取消</button>
            <button @click="confirmDelete" class="delete-confirm-btn" :disabled="deleting">
              {{ deleting ? '删除中...' : '确认删除' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { skillApi } from '../api/skill'
import { heroApi } from '../api/hero'

export default {
  name: 'SkillManagement',
  setup() {
    // 响应式数据
    const skills = ref([])
    const heroList = ref([])
    const loading = ref(false)
    const error = ref('')
    const searchQuery = ref('')
    const filterHeroId = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const totalCount = ref(0)
    
    // 模态框状态
    const showAddModal = ref(false)
    const showEditModal = ref(false)
    const showDeleteModal = ref(false)
    const submitting = ref(false)
    const deleting = ref(false)
    
    // 表单数据
    const formData = reactive({
      skillId: null,
      skillName: '',
      skillDescription: '',
      skillUrl: '',
      heroId: ''
    })
    
    const skillToDelete = ref(null)
    
    // 计算属性
    const filteredSkills = computed(() => {
      let result = skills.value
      
      if (searchQuery.value) {
        result = result.filter(skill => 
          skill.skillName.toLowerCase().includes(searchQuery.value.toLowerCase())
        )
      }
      
      if (filterHeroId.value) {
        result = result.filter(skill => skill.heroId === parseInt(filterHeroId.value))
      }
      
      return result
    })
    
    const totalPages = computed(() => {
      return Math.ceil(filteredSkills.value.length / pageSize.value)
    })
    
    const paginatedSkills = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return filteredSkills.value.slice(start, end)
    })
    
    // 方法
    const loadSkills = async () => {
      try {
        loading.value = true
        error.value = ''
        
        const response = await skillApi.getSkillList({
          current: 1,
          pageSize: 20 // 符合后端限制
        })
        
        if (response.code === 0) {
          skills.value = response.data.records || []
          totalCount.value = response.data.total || 0
        } else {
          throw new Error(response.message || '获取技能列表失败')
        }
      } catch (err) {
        console.error('加载技能列表失败:', err)
        error.value = err.message || '加载技能列表失败'
      } finally {
        loading.value = false
      }
    }
    
    const loadHeroes = async () => {
      try {
        const response = await heroApi.getAllHeroes()
        if (response.code === 0) {
          heroList.value = response.data || []
        }
      } catch (err) {
        console.error('加载英雄列表失败:', err)
      }
    }
    
    const forceRefresh = () => {
      loadSkills()
      loadHeroes()
    }
    
    const handleSearch = () => {
      currentPage.value = 1
    }
    
    const handleFilter = () => {
      currentPage.value = 1
    }
    
    const changePage = (page) => {
      currentPage.value = page
    }
    
    const editSkill = (skill) => {
      formData.skillId = skill.skillId
      formData.skillName = skill.skillName
      formData.skillDescription = skill.skillDescription
      formData.skillUrl = skill.skillUrl
      formData.heroId = skill.heroId
      showEditModal.value = true
    }
    
    const deleteSkill = (skill) => {
      skillToDelete.value = skill
      showDeleteModal.value = true
    }
    
    const closeModal = () => {
      showAddModal.value = false
      showEditModal.value = false
      resetForm()
    }
    
    const closeDeleteModal = () => {
      showDeleteModal.value = false
      skillToDelete.value = null
    }
    
    const resetForm = () => {
      formData.skillId = null
      formData.skillName = ''
      formData.skillDescription = ''
      formData.skillUrl = ''
      formData.heroId = ''
    }
    
    const submitForm = async () => {
      try {
        submitting.value = true
        
        const data = {
          skillName: formData.skillName,
          skillDescription: formData.skillDescription,
          skillUrl: formData.skillUrl,
          heroId: parseInt(formData.heroId)
        }
        
        let response
        if (showAddModal.value) {
          response = await skillApi.addSkill(data)
        } else {
          data.skillId = formData.skillId
          response = await skillApi.updateSkill(data)
        }
        
        if (response.code === 0) {
          closeModal()
          loadSkills()
        } else {
          throw new Error(response.message || '操作失败')
        }
      } catch (err) {
        console.error('提交失败:', err)
        alert(err.message || '操作失败')
      } finally {
        submitting.value = false
      }
    }
    
    const confirmDelete = async () => {
      try {
        deleting.value = true
        
        const response = await skillApi.deleteSkill(skillToDelete.value.skillId)
        
        if (response.code === 0) {
          closeDeleteModal()
          loadSkills()
        } else {
          throw new Error(response.message || '删除失败')
        }
      } catch (err) {
        console.error('删除失败:', err)
        alert(err.message || '删除失败')
      } finally {
        deleting.value = false
      }
    }
    
    const formatDate = (dateString) => {
      if (!dateString) return '-'
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN')
    }
    
    const truncateText = (text, maxLength) => {
      if (!text) return '-'
      if (text.length <= maxLength) return text
      return text.substring(0, maxLength) + '...'
    }
    
    // 生命周期
    onMounted(() => {
      loadSkills()
      loadHeroes()
    })
    
    return {
      skills,
      heroList,
      loading,
      error,
      searchQuery,
      filterHeroId,
      currentPage,
      totalPages,
      paginatedSkills,
      showAddModal,
      showEditModal,
      showDeleteModal,
      submitting,
      deleting,
      formData,
      skillToDelete,
      loadSkills,
      forceRefresh,
      handleSearch,
      handleFilter,
      changePage,
      editSkill,
      deleteSkill,
      closeModal,
      closeDeleteModal,
      submitForm,
      confirmDelete,
      formatDate,
      truncateText
    }
  }
}
</script>

<style scoped>
.skill-management {
  padding: 20px;
  background: rgba(0, 0, 0, 0.7);
  min-height: 100vh;
  color: #fff;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #00d4ff;
}

.page-title {
  font-size: 28px;
  font-weight: bold;
  color: #00d4ff;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.refresh-btn, .add-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.refresh-btn {
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
}

.refresh-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.add-btn {
  background: #00d4ff;
  color: #000;
}

.add-btn:hover {
  background: #00b8e6;
}

.search-section {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.search-input, .filter-select {
  padding: 10px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 5px;
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
  font-size: 14px;
}

.search-input {
  flex: 1;
  max-width: 300px;
}

.filter-select {
  min-width: 150px;
}

.filter-select option {
  background: rgba(20, 20, 20, 0.9);
  color: #fff;
}

.table-container {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 10px;
  overflow: hidden;
  margin-bottom: 20px;
}

.skill-table {
  width: 100%;
  border-collapse: collapse;
}

.skill-table th,
.skill-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.skill-table th {
  background: rgba(0, 212, 255, 0.2);
  color: #00d4ff;
  font-weight: bold;
}

.skill-row:hover {
  background: rgba(255, 255, 255, 0.05);
}

.skill-name-cell {
  font-weight: bold;
  color: #00d4ff;
}

.skill-desc-cell {
  max-width: 200px;
}

.skill-description {
  word-break: break-word;
}

.skill-link {
  color: #00d4ff;
  text-decoration: none;
}

.skill-link:hover {
  text-decoration: underline;
}

.no-resource {
  color: #999;
}

.action-cell {
  display: flex;
  gap: 5px;
}

.edit-btn, .delete-btn {
  padding: 5px 10px;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
}

.edit-btn {
  background: rgba(255, 193, 7, 0.8);
}

.delete-btn {
  background: rgba(220, 53, 69, 0.8);
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  margin: 20px 0;
}

.page-btn {
  padding: 8px 16px;
  border: 1px solid #00d4ff;
  background: rgba(0, 212, 255, 0.1);
  color: #00d4ff;
  border-radius: 5px;
  cursor: pointer;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-btn:hover:not(:disabled) {
  background: rgba(0, 212, 255, 0.2);
}

.loading-container, .error-container {
  text-align: center;
  padding: 40px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-top: 4px solid #00d4ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: #1a1a1a;
  border-radius: 10px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.modal-header h3 {
  margin: 0;
  color: #00d4ff;
}

.close-btn {
  background: none;
  border: none;
  color: #fff;
  font-size: 24px;
  cursor: pointer;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  color: #fff;
  font-weight: bold;
}

.form-input, .form-select, .form-textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 5px;
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
  font-size: 14px;
  box-sizing: border-box;
}

.form-select option {
  background: rgba(20, 20, 20, 0.9);
  color: #fff;
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.cancel-btn, .submit-btn, .delete-confirm-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
}

.cancel-btn {
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
}

.submit-btn {
  background: #00d4ff;
  color: #000;
}

.delete-confirm-btn {
  background: #dc3545;
  color: #fff;
}

.warning-text {
  color: #ff6b6b;
  font-size: 14px;
  margin: 10px 0;
}

.delete-modal {
  max-width: 400px;
}
</style>